package com.me.mygdxgame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Array;
import com.me.mygdxgame.models.AbstractGameObject;
import com.me.mygdxgame.models.GoldCoin;

public class Level {

	public static final String TAG = Level.class.getName();
	public Array<GoldCoin> goldCoins;
	
	public enum BLOCK_TYPE{
		EMPTY(0, 0, 0), 
		ITEM_GOLD_COIN(255, 255, 0),
		ITEm_GUN(150, 100, 50),
		ITEm_POT_GOLD(255, 150, 0);
		
		private int color;
		
		private BLOCK_TYPE(int r, int g, int b){
			color = r<<24|g<<16|b<<8|0xff;
		}
		
		public boolean sameColor(int color){
			return this.color == color;
		}
	}
	
	public Level(String filename){
		init(filename);
	}
	
	private void init(String filename){
		
		goldCoins = new Array<GoldCoin>();
		
		Pixmap pixmap = new Pixmap(Gdx.files.internal(filename));
		int lastPixel = -1;
		for (int pixelY = 0; pixelY < pixmap.getHeight(); pixelY++) {
			for (int pixelX = 0; pixelX < pixmap.getWidth(); pixelX++) {
				AbstractGameObject obj = null;
				float offsetHeight = 0;
				float baseHeight = pixmap.getHeight() - pixelY;
				int currentPixel = pixmap.getPixel(pixelX, pixelY);
				if(BLOCK_TYPE.EMPTY.sameColor(currentPixel)){
					
				}else if(BLOCK_TYPE.ITEM_GOLD_COIN.sameColor(currentPixel)){
					obj = new GoldCoin();
					offsetHeight = 0;
					obj.sprite.setPosition(pixelX*obj.sprite.getWidth(), (pixmap.getHeight() -pixelY - 1)*obj.sprite.getHeight());
					goldCoins.add((GoldCoin)obj);
					Gdx.app.log(TAG, "coins");
				}else if(BLOCK_TYPE.ITEm_GUN.sameColor(currentPixel)){
					
				}
				else{
//					int r = 0xff & (currentPixel >>> 24);
//					int g = 0xff & (currentPixel >>> 16);
//					int b = 0xff & (currentPixel >>> 8);
//					int a = 0xff & currentPixel;
//					Gdx.app.error(TAG, "Unknown object at x<" + pixelX
//							+ "> y<" + pixelY
//							+ ">: r<" + r
//							+ "> g<" + g
//							+ "> b<" + b
//							+ "> a<" + a + ">");
				}
				lastPixel = currentPixel;
			}
		}
		pixmap.dispose();
		Gdx.app.debug(TAG, "level '" + filename + "' loaded");
	}
	
	public void render(SpriteBatch batch){
		for(GoldCoin goldCoin : goldCoins){
			goldCoin.render(batch);
		}
	}
}
